import { reactive } from 'vue'

interface UserState {
  isInitial: boolean
  isLogin: boolean
  isHH: boolean
  key: string
  signature: string
}

export enum LoginLocalStorageKey {
  key = '__LOGIN_KEY__',
  signature = '__LOGIN_SIGNATURE__',
  session = '__LOGIN_SESSION__'
}

let userStore: UserState = {
  isLogin: false,
  isInitial: false,
  isHH: false,
  key: '',
  signature: ''
}

export function setupLoginStore() {

  userStore = reactive<UserState>({
    isLogin: false,
    isInitial: false,
    isHH: false,
    key: '',
    signature: ''
  })

  const { HeyheyBridge } = window
  userStore.isHH = window.isHeyHeyTalk && window.isHeyHeyTalk()

  if (userStore.isHH) {
    localStorage.removeItem(LoginLocalStorageKey.key)
    localStorage.removeItem(LoginLocalStorageKey.session)
    HeyheyBridge.request({ action: 'login', data: '' }, (e: any) => {
      try {
        const data = JSON.parse(e.data)
        if (Number(data.Role) !== 2) { // 不是游客
          const { Key, SessionId } = data
          localStorage.setItem(LoginLocalStorageKey.key, Key)
          localStorage.setItem(LoginLocalStorageKey.session, SessionId)
          localStorage.setItem('Us_info___', JSON.stringify(data))
          userStore.isLogin = true
          userStore.key = Key
        }
      } catch (err) {
        if (e === null) { // 注册失败
          window.location.reload()
          return false
        }
      }
      userStore.isInitial = true
    })
  } else {
    userStore.isInitial = true
    if(localStorage.getItem(LoginLocalStorageKey.key)) {
      userStore.isLogin = true
      userStore.key = encodeURIComponent(localStorage.getItem(LoginLocalStorageKey.key) || '')
      userStore.signature = encodeURIComponent(localStorage.getItem(LoginLocalStorageKey.signature) || '')
    }
  }

}

export function useLoginStore(): UserState {
  return userStore
}


export function clearLoginStore() {
  localStorage.removeItem(LoginLocalStorageKey.key)
  localStorage.removeItem(LoginLocalStorageKey.session)
  localStorage.removeItem(LoginLocalStorageKey.signature)
  const userStore = useLoginStore()
  if(userStore) {
    userStore.isLogin = false
  }
}
